class Promise {
  // 接收一个函数，定义为executor(执行者)
  constructor(executor) {
    // 参数校验 备注：原生Promise传入Number数字1时报：TypeError: Promise resolver 1 is not a function
    if(typeof executor !=='function') {
      throw new TypeError(`TypeError: Promise resolver ${executor} is not a function`)
    }
    this.initValue();
    this.initBind();
    // 传递给executor
    executor(this.resolve,this.reject)
  }
  // 绑定this
  initBind() {
    this.resolve = this.resolve.bind(this)
    this.reject = this.reject.bind(this)
  }
  // 初始化值
  initValue() {
    this.value = null // 终值
    this.resson =null // 拒因
    this.state = 'pending' // 默认状态，状态一旦改变则不可逆转
  }
  // 定义 resolve函数和reject函数
  resolve(value) {
    // 成功后的操作(状态的改变，成功回调的执行)
    if(this.state === 'pending') {
      this.state = 'fulfilled'
      this.value = value
    }
  }
  reject(reason) {
    // 失败后的操作(状态的改变，失败回调的执行)
    if(this.state === 'pending') {
      this.state = 'rejected '
      this.resson = reason
    }
  }
}

// 导出
module.exports = Promise